#!/usr/bin/env python
import re
import os
import sys

filename = "students.txt"

def main():
    ctrl = True # 退出系统标记
    while (ctrl):
        menu()
        option = input("请选择：")
        option_str = re.sub("\D", "", option)
        if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
            option_int = int(option_str)
            if option_int == 0:
                print("您已退出学生信息管理系统！")
                ctrl = False
                sys.exit(0)
            elif option_int == 1:
                ## 录入成绩
                insert()
            elif option_int == 2:
                ## 查找成绩
                search()
            elif option_int == 3:
                ## 删除成绩
                delete()
            elif option_int == 4:
                ## 修改成绩
                modify()
            elif option_int == 5:
                ## 排序
                sort()
            elif option_int == 6:
                ## 统计
                total()
            elif option_int == 7:
                ## 显示所有学生信息
                show()
        else:
            print("错误的输入，请重新输入。")


## 输出菜单
def menu():
    print("""
    ===============学生信息管理系统==============

       ============= 功能菜单 ===============

       1 录入学生信息
       2 查找学生信息
       3 删除学生信息
       4 修改学生信息
       5 排序
       6 统计学生总人数
       7 显示所有学生信息
       0 退出系统

       ======================================
       说明：通过数字或上下方向键选择菜单

    ============================================
    """)

## 信息保存
def save(student):
    try:
        students_txt = open(filename, "a")
    except:
        students_txt = open(filename, "w")
    for info in student:
        students_txt.write(str(info) + "\n")
    students_txt.close()

## 插入
def insert():
    student_list = []
    mark = True
    while mark:
        id = input("请输入ID（如 1001）：")
        if not id:
            break
        name = input("请输入名字：")
        if not name:
            break
        try:
            english = int(input("请输入英语成绩："))
            python = int(input("请输入 python 成绩："))
            c = int(input("请输入 C 语言成绩："))
        except:
            print("输入无效，不是整数数值... 请重新录入。")
            continue
        ## 保存信息到字典
        student = {"id": id, "name": name, "english": english, "python": python, "c": c}
        student_list.append(student)

        input_mark = input("是否继续添加？（y/n）：")
        if input_mark.lower().startswith('y'):
            mark = True
        else:
            mark = False

        save(student_list)
        print("学生信息录入完毕！")

def delete():
    mark = True
    while mark:
        studentId = input("请输入要删除的学生ID：")
        if studentId is not "":
            if os.path.exists(filename):
                with open(filename, "r") as rfile:
                    studentOld = rfile.readlines()  # 读取全部内容
            else:
                studentOld = []
            ifdel = False
            if studentOld:
                with open(filename, "w") as wfile:
                    d = {}
                    for list in studentOld:
                        d = dict(eval(list))
                        if d['id'] != studentId:
                            wfile.write(str(d) + "\n")
                        else:
                            ifdel = True
                    if ifdel:
                        print("ID为 %s 的学生信息已经删除..." % studentId)
                    else:
                        print("没有找到ID为 %s 的学生信息..." %studentId)
            else:
                print("无学生信息。")
                break
            #show() # 显示全部学生信息
            inputMark = input("是否继续删除？（y/n）：")
            if inputMark.lower().startswith('y'):
                mark = True
            else:
                mark = False

def modify():
    show()
    if os.path.exists(filename):
        with open(filename, 'r') as rfile:
            student_old = rfile.readlines()
    else:
        return

    studentid = input("请输入要修改的学生ID：")
    with open(filename, 'w') as wfile:
        for student in student_old:
            d = dict(eval(student))
            if d['id'] == studentid:
                print("找到了这名学生，可以修改他的信息：")
                while True:
                    try:
                        d['name'] = input("请输入姓名：")
                        d['english'] = int(input('请输入英语成绩：'))
                        d['python'] = int(input('请输入 Python 成绩：'))
                        d['c'] = int(input('请输入 C 语言成绩：'))
                    except:
                        print("您的输入有误，请重新输入。")
                    else:
                        break
                student = str(d)
                wfile.write(student + "\n")
                print("修改成功！")
            else:
                wfile.write(student)
    mark = input("是否继续修改学生信息？（y/n）")
    if mark == "y":
        modify

## 程序入口
if __name__ == "__main__":
    main()